import axios from "axios"
import qs from "qs"
import { successAlert } from "../utils/alert"
import store from "../store"
import { actions } from "../store/modules/login"
// 请求拦截
axios.interceptors.request.use(config=>{
    if(config.url!=="/api/register"&&config.url!=="/api/login"){
        config.headers.authorization=JSON.parse(localStorage.getItem("userInfo")).token
    }
    return config;
})

// 响应拦截
axios.interceptors.response.use(res=>{
    // 统一打印结果
    console.group("本次响应请求地址:"+res.config.url)
    console.log(res)
    console.groupEnd();

    // 统一处理非成功响应
    if(res.data.code !== 200){
        successAlert(res.data.msg)
    }
    // 统一掉线处理
    if(res.data.msg==="登录已过期或访问权限受限"){
        //清除redux和本地存储的数据
        store.dispatch(actions.changeInfo({}))
        //跳转页面
        window.open("http://localhost:58896/","_self")
    }

    return res
})

// 封装get和post
export const get = (url, params={})=>{
    return axios({
        url,
        method:'get',
        params
    })
}

export const post = (url, params={}, haveFile=false)=>{
    let data;
    if(haveFile){
        data = new FormData();
        Object.keys(params).forEach(key=>{
            data.append(key, params[key])
        }); 
    }else{
        data = new URLSearchParams(params).toString()
    }

    return axios({
        url,
        method:'post',
        data
    })
}